<template>
  <el-card style="width: 100%">
    <el-table :data="prodcuList" style="width: 100%">
      <el-table-column prop="id" label="序号" flex="1" align="center" />
      <el-table-column prop="title" label="商品名称" flex="1" align="center" />
      <el-table-column prop="price" label="商品价格" flex="1" align="center" />
      <el-table-column prop="number" label="库存" flex="1" align="center" />
      <el-table-column label="操作" flex="1" align="center">
        <template #default="scope">
          <el-button type="success" @click="addBuyCar(scope.row)">添加到购物车</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getProducts } from '@/api/product.js'
import { useBuyCarStores } from '@/stores/stores.js'
const stores = useBuyCarStores()
const { addProduct2ByCarList } = stores
const prodcuList = ref([])
onMounted(async () => {
  prodcuList.value = await getProducts()
})

const addBuyCar = (item) => {
  if (item.number > 0) {
    addProduct2ByCarList(item)
    item.number--
  } else {
    //弹出警告弹窗
    ElMessage({
      duration: 3000,
      message: '库存为0,不能加入购物车',
      type: 'error'
    })
  }
}
</script>

<style scoped>
</style>